using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Ornament.Domain;
using Ornament.MemberShip;
using Ornament.MemberShip.Permissions;
using Ornament.NHibernates;

namespace Ornament.Web
{
    /// <summary>
    /// </summary>
    public sealed class OrnamentContext
    {
        /// <summary>
        /// </summary>
        private static readonly OrnamentContext Instance = new OrnamentContext();


        /// <summary>
        /// Prevents a default instance of the <see cref="OrnamentContext"/> class from being created. 
        /// </summary>
        private OrnamentContext()
        {
        }

        /// <summary>
        /// Gets Current.
        /// </summary>
        /// <value>
        /// The current context.
        /// </value>
        public static OrnamentContext Current
        {
            get { return Instance; }
        }

        /// <summary>
        /// 
        /// </summary>
        public User CurrentUser
        {
            get
            {
                if (HttpContext.Current == null || HttpContext.Current.User == null ||
                    !HttpContext.Current.User.Identity.IsAuthenticated)
                    return null;
                  
                SessionManager.Instance.IniSession();
                User user =
                    GetDaoFactory<IMemberShipFactory>().CreateUserDao().Get(HttpContext.Current.User.Identity.Name);
                if (user != null)
                {
                    return user;
                }
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static ResourceDescriptionManager Configuration
        {
            get { return Inner.Instance.GetContainer().Resolve<ResourceDescriptionManager>("Configuration"); }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetDaoFactory<T>()
        {
            return Inner.Instance.GetContainer().Resolve<T>();
        }

        /// <summary>
        /// get operator type form ResourceInfo
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static Type GetOperatorType(object resource)
        {
            var mapping = Inner.Instance.GetContainer().Resolve<OperatorResourceMapping>();
            if (resource is string)
                return mapping[resource.ToString()];
            return mapping[resource.GetType()];
        }

        public static IList<string> GetTypeResource()
        {
            var mapping = Inner.Instance.GetContainer().Resolve<OperatorResourceMapping>();
            return mapping.TypeResourceMapping.Keys.ToList();
        }

        public bool HasRight(Type objRes, string id, Enum @operator)
        {
            var membershipFactory = GetDaoFactory<IMemberShipFactory>();
            object res;
            try
            {
                res = membershipFactory.CreateResourceDao().Load(objRes, id);
            }
            catch (Exception ex)
            {
                throw new OrnamentException(String.Format("Can't find the resource {0}, id={1}", objRes.FullName, id),
                                            ex);
            }
            return HasRight(res, @operator);
        }

        public bool HasRight(Type objRes, object id, Enum @operator)
        {
            var membershipFactory = GetDaoFactory<IMemberShipFactory>();
            object res;
            try
            {
                res = membershipFactory.CreateResourceDao().Load(objRes, id);
            }
            catch (Exception ex)
            {
                throw new OrnamentException(String.Format("Can't find the resource {0}, id={1}", objRes.FullName, id),
                                            ex);
            }
            return HasRight(res, @operator);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="operators"></param>
        /// <returns></returns>
        public bool HasRight(object resource, Enum operators)
        {
            if (resource == null)
                throw new ArgumentNullException("resource");
            if (Convert.ToInt32(operators) == 0)
                return false;
            var permissionDao = GetDaoFactory<IMemberShipFactory>().PermissionDao(false);
            IList<Permission> permissions = permissionDao.GetUserPermissions(HttpContext.Current.User.Identity.Name, resource);

            return
                permissions.Any(permission => permission.Resource.Equals(resource) && permission.HasOperator(operators));
        }

        public static object GetResource(Type resourceType, object resourceId)
        {
            if (resourceType == typeof(string))
                return resourceId;
            return Current.GetDaoFactory<IMemberShipFactory>().CreateResourceDao().Get(resourceType, resourceId);
        }

        public static object GetResource(Type resourceType, string resourceId)
        {
            return resourceType == typeof(string)
                       ? resourceId
                       : Current.GetDaoFactory<IMemberShipFactory>().CreateResourceDao().Get(resourceType, resourceId);
        }

        #region Nested type: Inner

        private class Inner
        {
            // ReSharper disable MemberHidesStaticFromOuterClass
            public static readonly Inner Instance = new Inner();
            // ReSharper restore MemberHidesStaticFromOuterClass

            private Inner()
            {
            }

            public IWindsorContainer GetContainer()
            {
                var container = new WindsorContainer(new XmlInterpreter());
                return container;
            }
        }

        #endregion
    }
}